/*
https://leetcode.cn/problems/next-greater-element-iii/submissions/581499804/
*/
class Solution {
public:
vector<int> findLeftSmaller(vector<int>& nums) {
        vector<int> result(nums.size(), -1);
        stack<int> st;
        for (int i = 0; i < nums.size(); ++i) {
            while (!st.empty() && nums[i] < nums[st.top()]) {
                result[st.top()] = nums[i];
                st.pop();
            }
            st.push(i);
        }
        return result;
    }

    int nextGreaterElement(int n) {
        long long ans=0;
        string src=to_string(n);
        int size=src.size();
        stack<int> st;
        int idx=0;
        int i=size-1;
        for(;i>=0;--i){
            while(!st.empty()&&(src[i]<src[st.top()])){
                idx=st.top();
                st.pop();
            }
            if(idx!=0){
                int tmp=src[i];
                src[i]=src[idx];
                src[idx]=tmp;
                break;
            }
            st.push(i);
        }
        if(idx==0) return -1;
        sort(src.begin()+i+1,src.end());
        ans=stoll(src);
        if(ans>INT_MAX)return -1;
        return ans;
    }
};